import router from '../router'
import localStorage from '../utils/localStorage'
import { isEmpty } from 'element-ui/src/utils/util'

export default {
  state: {
    routerListState: [],
    isCollapseState: false,
    projectNameState: 'AdminVueThinkPHP',
    elIconSFoldUnfoldIconState: 'el-icon-s-fold',
    clickMenuState: '',
    clickMenuPath: ''
  },

  mutations: {
    menuListMutations(state) {
      console.log('abcedfdfd')
      const adminRules = localStorage.get('rules', true)
      console.log(state.routerListState.length)
      if (!adminRules || state.routerListState.length !== 0) return true

      let pathRouter = ''
      let nameRouter = ''
      const routerList = [{
        path: '/',
        name: '/Home',
        component: () => import('../views/home/Home'),
        children: []
      },
      { path: '*', redirect: '/404' }]

      adminRules.forEach(function(v) {
        if (v.pid !== 0) {
          nameRouter = v.path.split('/').pop()
          pathRouter = nameRouter.charAt(0).toLowerCase() + nameRouter.slice(1) // 路径转换成小写

          console.log(nameRouter + '/' + pathRouter)
          // 将二级导航权限注册到首页Home组件的子路由中
          routerList[0].children.push({
            path: `/${pathRouter}`,
            name: nameRouter,
            component: () => import('@/views/' + v.path + '.vue'),
            meta: {
              truePath: v.path
            }
          })
        } else {
          routerList[0].children.push({
            path: `/${v.name}`,
            name: v.name,
            component: () => import('@/views/' + v.path + ''),
            meta: {
              truePath: v.path
            }
          })
        }
      })

      state.routerListState = routerList // 保存到store中
      router.addRoutes(state.routerListState) // 将menu注册到动态路由中
    },

    collapseMenuMutations(state) {
      state.isCollapseState = !state.isCollapseState
    },

    clickMenuMutations(state, param) {
      let value = param.name
      if (typeof value === 'object' && value !== null) value = value.pop()
      state.clickMenuState = value
      state.clickMenuPath = param.meta.truePath
      // console.log(param)
    },

    // 生产路由，导航菜单
    rulesMutations(state, value) {
      const menuList = []

      // 获取顶级模块菜单
      value.forEach(v => {
        if (v.pid !== 0 || v.enable !== 2 || v.menu !== 2) return true
        v.children = []
        menuList.push(v)
      })

      // 生成二级子菜单
      if (!isEmpty(menuList)) {
        menuList.forEach((v, k) => {
          value.forEach(v2 => {
            if (v2.pid !== v.id || v2.enable !== 2 || v2.menu !== 2) return true
            menuList[k].children.push(v2)
          })
        })
      }
      localStorage.set('menuList', menuList)
      localStorage.set('rules', value)

      this.commit('menuListMutations')
    }
  },

  actions: {

  }
}
